<template>
  <div class="area-selector">
    <el-cascader
      v-model="selectedValue"
      :options="formattedRegionData"
      :props="props"
      @change="handleChange"
      placeholder="请选择省/市/区"
      style="display: block;"
    ></el-cascader>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  regionData: {
    type: Array,
    required: true
  },
  codeToText: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const selectedValue = ref([])

const cascaderProps = {
  expandTrigger: 'hover',
  value: 'value',
  label: 'label',
  children: 'children',
  emitPath: true
}

const formattedRegionData = computed(() => {
  return props.regionData.map(province => ({
    value: province.value,
    label: province.label,
    children: province.children.map(city => ({
      value: city.value,
      label: city.label,
      children: city.children.map(area => ({
        value: area.value,
        label: area.label
      }))
    }))
  }))
})

watch(() => props.modelValue, (newVal) => {
  selectedValue.value = newVal
}, { immediate: true })

const handleChange = (value) => {
  emit('update:modelValue', value)
  emit('change', value)
}
</script>

<style scoped>
.area-selector {
  width: 100%;
}
</style>